package com.hx.order.listener;

import com.hx.common.api.OrderService;
import com.hx.common.domain.MiaoshaOrder;
import com.hx.common.domain.OrderInfo;
import com.hx.common.to.OrderMessageTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;


/**
 * @Author wonghiu
 * @Date 2021/6/6 10:45
 * @Version 1.0.1
 */
@Slf4j
@Component
@RabbitListener(queues = "order.release.order.queue")
// 订单创建后，发送消息到order.create.order队列，该队列会定时过期
// 过期后消息变为死信转发到order.release.order队列即当前队列
// 一旦监听到死信，则对死信对应订单进行关单
public class OrderReleaseListener {
    @Autowired
    private OrderService orderService;

    @RabbitHandler
    @Transactional
    public void listener(OrderMessageTo orderMessageTo, Channel channel, Message message) throws IOException{
        try {
            log.info("收到关单请求。。。");
            // 超时后，只有订单状态为新建时才能关单，否则可能已经被支付
            System.out.println(orderMessageTo.getOrderId());
            OrderInfo miaoshaOrderUpdate = orderService.getOrderById(orderMessageTo.getOrderId());
            System.out.println(miaoshaOrderUpdate);
            if (miaoshaOrderUpdate.getStatus()==0){
                // 关单，则将订单状态改为【已取消】
                orderService.updateOrderStatusById(orderMessageTo.getOrderId(),2);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }

        }catch (Exception e){
            System.out.println(e);
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
